package com.hixtrip.sample.app.convertor;

import com.hixtrip.sample.client.order.dto.CommandOderCreateDTO;
import com.hixtrip.sample.client.order.dto.CommandPayDTO;
import com.hixtrip.sample.domain.order.model.Order;
import com.hixtrip.sample.domain.pay.model.CommandPay;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;

import java.math.BigDecimal;
import java.util.Random;

/**
 * DTO对像 -> 领域对象转换器
 * 转换器
 */
//@Mapper
public interface OrderConvertor {

//    OrderConvertor INSTANCE = Mappers.getMapper(OrderConvertor.class);

      static CommandPay commandPayBuildByDTO(CommandPayDTO dto){
//        BeanUtils.copyProperties();
        CommandPay commandPay = new CommandPay();
        commandPay.setPayStatus(dto.getPayStatus());
        commandPay.setOrderId(dto.getOrderId());
        return commandPay;
    }
    static Order OrderBuild(CommandOderCreateDTO commandOderCreateDTO, BigDecimal money){
        Order order = new Order();
        //模拟id
        order.setId(String.valueOf(getTableIndexFromUserId(Long.parseLong(commandOderCreateDTO.getUserId()),generateSixDigitNumber())));
        order.setAmount(commandOderCreateDTO.getAmount());
        order.setMoney(money);
        order.setUserId(commandOderCreateDTO.getUserId());
        order.setSkuId(commandOderCreateDTO.getSkuId());
        order.setPayStatus("0");
        return order;
    }

    /**
     * 基因切片
     * @param userId
     * @return
     */
    static Long getTableIndexFromUserId(long userId,long orderId){
        //4张表
        String v = String.format("%07d",Integer.parseInt((Long.toBinaryString(userId & (4-1)))));
        return Long.parseLong(Long.toBinaryString(orderId)+v,2);
    }

    /**
     * 模拟随机订单号
     * @return
     */
     static Long generateSixDigitNumber() {
        StringBuilder sb = new StringBuilder();

        Random random = new Random();

        for (int i = 0; i < 6; i++) {

            int digit = random.nextInt(10);
            sb.append(digit);
        }

        return Long.parseLong(sb.toString());
    }
}
